package com.ansion.baseui.base.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;

import com.ansion.CommonDataCallback;
import com.ansion.basedb.dao.LoginedUserMgr;
import com.ansion.basedb.dao.model.CurrentUser;
import com.ansion.basetool.preconditions.Preconditions;
import com.ansion.baseui.R;
import com.ansion.constant.BConstant;
import com.ansion.user.UserSdkFactory;
import com.ansion.user.beanforui.ContactInfo;
import com.ansion.user.listener.ContactChangeListener;
import com.ansion.utils.ColorStringUtils;
import com.ansion.utils.ContactUtil;
import com.ansion.utils.ResourceUtils;
import com.ansion.utils.ThreadUtil;
import com.ansion.utils.UiUtils;
import com.ansion.utils.thread.SafeRunnable;


/**
 * created by zhaoyuntao
 * on 06/10/2020
 * description:
 */
public class UserNameView extends FrameLayout {
    //If current user in contact book, hide child.
    protected TextView mTitle;
    private View mVipBadge, mWalletBadge;
    private SimpleDraweeViewFix mFlag;
    private TextView followView;

    private boolean showFollowView;
    private CharSequence nameNotProcessed;
    private ContactChangeListener contactChangeListener;
    private TextProcessor textProcessor;
    private String tag2;
    private boolean showYou = true;
    private boolean showVip = true;
    private boolean showBadgeWallet = false;
    private boolean alwaysShowNickname;
    //是否是会话列表
    private boolean isSession;
    //是否是MissedCall
    private boolean isMissedCall;
    private boolean showNickname;
    private String keywords;
    private Integer highlightColor;
    private int textColor;
    private boolean showSymbol = true;

    private String badgeMpFrom;

    public UserNameView(Context context) {
        super(context);
        initAttr(null);
    }

    public UserNameView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initAttr(attrs);
    }

    public UserNameView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttr(attrs);
    }

    private void initAttr(@Nullable AttributeSet attrs) {
        initLayout();
        int mTitleSize;
        int mTitleMaxWidth;
        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.UserNameView);
            showYou = typedArray.getBoolean(R.styleable.UserNameView_showYou, true);
            showVip = typedArray.getBoolean(R.styleable.UserNameView_showVip, true);
            showBadgeWallet = typedArray.getBoolean(R.styleable.UserNameView_showBadgeWallet, false);//默认false
            alwaysShowNickname = typedArray.getBoolean(R.styleable.UserNameView_alwaysShowNickname, false);
            mTitleSize = (int) typedArray.getDimension(R.styleable.UserNameView_titleSize, UiUtils.spToPx(12));
            if (typedArray.hasValue(R.styleable.UserNameView_android_textSize)) {
                mTitleSize = typedArray.getDimensionPixelSize(R.styleable.UserNameView_android_textSize, UiUtils.spToPx(18));
            }
            textColor = typedArray.getColor(R.styleable.UserNameView_titleColor, 0);
            if (typedArray.hasValue(R.styleable.UserNameView_android_textColor)) {
                textColor = typedArray.getColor(R.styleable.UserNameView_android_textColor, ResourceUtils.getColor(R.color.contact_name_color));
            }
            mTitleMaxWidth = typedArray.getDimensionPixelSize(R.styleable.UserNameView_maxWidth, -1);

            typedArray.recycle();
        } else {
            textColor = ResourceUtils.getColor(R.color.bot_level1_base_color);
            showYou = true;
            showVip = true;
            showBadgeWallet = false;//默认false
            alwaysShowNickname = false;
            mTitleSize = -1;
            mTitleMaxWidth = -1;
        }
        if (mTitleSize > 0) {
            mTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTitleSize);
        }
        if (textColor != 0) {
            mTitle.setTextColor(textColor);
        }
        if (mTitleMaxWidth != -1) {
            mTitle.setMaxWidth(mTitleMaxWidth);
        }
    }

    public void setShowVip(boolean showVip) {
        this.showVip = showVip;
    }
    public void setShowBadgeWallet(boolean showBadgeWallet) {
        this.showBadgeWallet = showBadgeWallet;
    }

    private void initLayout() {
        View inflate = View.inflate(getContext(), R.layout.vip_title_view, this);
        mTitle = inflate.findViewById(R.id.title);
        mVipBadge = inflate.findViewById(R.id.badge_vip);
        mWalletBadge = inflate.findViewById(R.id.badge_wallet);
        mFlag = inflate.findViewById(R.id.official_flag);

        mVipBadge.setOnClickListener(v -> {
            gotoBadgeExplanationHome(TextUtils.isEmpty(badgeMpFrom) ? "" : BConstant.MPFrom.FROM_BADGE_VIP + badgeMpFrom);
        });
        mWalletBadge.setOnClickListener(v -> {
            gotoBadgeExplanationHome(TextUtils.isEmpty(badgeMpFrom) ? "" : BConstant.MPFrom.FROM_BADGE_WALLET + badgeMpFrom);
        });
    }

    public void setBadgeMpFrom(String badgeMpFrom){
        this.badgeMpFrom = badgeMpFrom;
    }

    private void gotoBadgeExplanationHome(String mpFrom) {
        boolean vipEnable = mVipBadge.getVisibility() == VISIBLE;
        boolean walletEnable = mWalletBadge.getVisibility() == VISIBLE;
//        BotRouter.gotoBadgeExplanationHome(mTitle.getText().toString(), vipEnable, walletEnable, mpFrom);
    }

    public void setFollowView(@NonNull TextView followView) {
        setFollowView(followView, true);
    }

    public void setFollowView(@NonNull TextView followView, boolean showSymbol) {
        Preconditions.checkNotNull(followView);
        this.followView = followView;
        this.followView.setVisibility(GONE);
        this.showFollowView = false;
        this.showSymbol = showSymbol;
    }

    public void bindUid(@NonNull String userUid) {
        bindUid(userUid, false, false, false);
    }

    public void bindUid(@NonNull String userUid, boolean showNickname) {
        bindUid(userUid, false, false, showNickname);
    }

    public void setHighlight(String keywords, @ColorRes Integer highlightColor) {
        this.keywords = keywords;
        this.highlightColor = highlightColor;
    }

    public void bindUid(@NonNull String userUid, boolean isSession, boolean isMissedCall) {
        this.isSession = isSession;
        this.isMissedCall = isMissedCall;
        this.showNickname = false;
        initListener(userUid);
        setTag2(userUid);
        loadContactName(userUid);
    }

    public void bindUid(@NonNull String userUid, boolean isSession, boolean isMissedCall, boolean showNickname) {
        this.isSession = isSession;
        this.isMissedCall = isMissedCall;
        this.showNickname = showNickname;
        initListener(userUid);
        setTag2(userUid);
        loadContactName(userUid);
    }

//    public void bindUid(@NonNull UserNameParams params) {
//        this.isSession = params.isSession();
//        this.isMissedCall = params.isMissedCall();
//        this.showNickname = params.isShowNickname();
//        this.showFollowView = params.isShowFollowView();
//        this.alwaysShowNickname = params.isAlwaysShowNickname();
//        this.showSymbol = params.isShowSymbol();
//        this.showYou = params.isShowYou();
//        this.showVip = params.isShowVip();
//        this.showBadgeWallet = params.isShowBadgeWallet();
//        this.textProcessor = params.getTextProcessor();
//        this.keywords = params.getKeywords();
//        this.highlightColor = params.getHighlightColor();
//
//        if (params.hasTextColor()) {
//            this.textColor = params.getTextColor();
//        } else if (params.hasTextColorRes()) {
//            this.textColor = ResourceUtils.getColor(params.getTextColorRes());
//        }
//        setTextColor(textColor);
//        initListener(params.getUid());
//        setTag2(params.getUid());
//        loadContactName(params.getUid());
//    }

    public void setVerifyIcon(int iconId) {
        if (iconId > 0) {
            Drawable drawable = getContext().getResources().getDrawable(iconId);
            if (UiUtils.isRTLLanguage()) {
                mTitle.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
            } else {
                mTitle.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
            }
        } else {
            mTitle.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }
    }


    private void initListener(String userUid) {
        if (TextUtils.isEmpty(userUid)) {
            return;
        }
        if (contactChangeListener == null) {
            contactChangeListener = new ContactChangeListener() {

                @Override
                public void onNameChanged(@NonNull String uid) {
                    ThreadUtil.runUi(new SafeRunnable(UserNameView.this) {
                        @Override
                        protected void runSafely() {
                            if (!TextUtils.equals(uid, UserNameView.this.getTag2())) {
                                return;
                            }
                            loadContactName(uid);
                        }
                    });
                }


                @Override
                public void onVipChanged(@NonNull String uid, boolean isVip) {
                    ThreadUtil.runUi(new SafeRunnable(UserNameView.this) {
                        @Override
                        protected void runSafely() {
                            if (!TextUtils.equals(uid, UserNameView.this.getTag2())) {
                                return;
                            }
                            setVip(isVip);
                        }
                    });
                }

                @Override
                public void onWalletChanged(@NonNull String uid, boolean isWallet) {
                    ThreadUtil.runUi(new SafeRunnable(UserNameView.this) {
                        @Override
                        protected void runSafely() {
                            if (!TextUtils.equals(uid, UserNameView.this.getTag2())) {
                                return;
                            }
                            setBadgeWallet(isWallet);
                        }
                    });
                }

                @Override
                public void onDeleteAccount(@NonNull String uid) {
                    ThreadUtil.runUiSafely(getContext(), () -> {
                        if (!TextUtils.equals(uid, UserNameView.this.getTag2())) {
                            return;
                        }
                        if (followView != null) {
                            followView.setVisibility(GONE);
                        }
                    });
                }

                @Override
                public void onOaVerifiedChange(@NonNull String uid, String iconUrl) {
                    ThreadUtil.runUiSafely(getContext(), () -> {
                        if (!TextUtils.equals(uid, UserNameView.this.getTag2())) {
                            return;
                        }
                        setOAVerify(iconUrl);
                    });
                }
            };
        }
        contactChangeListener.init(userUid);
        UserSdkFactory.getSdk().registerContactListener(contactChangeListener);
    }


    @Override
    public void setOnClickListener(@Nullable OnClickListener l) {
        super.setOnClickListener(l);
        if (followView != null) {
            followView.setOnClickListener(l);
        }
    }

    private void loadContactName(String userUid) {
        UserSdkFactory.getSdk().getContactInfo(userUid, showNickname, new CommonDataCallback<ContactInfo>() {
            @Override
            public void onSuccess(ContactInfo contactInfo) {
                ThreadUtil.runUi(new SafeRunnable(getContext()) {
                    @Override
                    protected void runSafely() {
                        if (ContactUtil.isSelf(userUid) && showYou) {
                            String name = ResourceUtils.getString(R.string.inbox_group_you);
                            setName(name);
                            if (alwaysShowNickname) {
                                CurrentUser currentUser = LoginedUserMgr.getCurrentLoginedUser();
                                setFollowViewName(currentUser != null ? currentUser.getNickName() : null);
                            } else {
                                setFollowViewName(null);
                            }
                            mFlag.setVisibility(GONE);
                        } else {
                            if (contactInfo == null) {
                                setName(userUid);
                                return;
                            }
                            if (!TextUtils.equals(contactInfo.getUid(), UserNameView.this.getTag2())) {
                                setName(null);
                                return;
                            }
                            if (isSession) {//正常列表
                                if (ContactUtil.isGroup(userUid) && contactInfo.isGroupVoip()) {
                                    mTitle.setEllipsize(TextUtils.TruncateAt.MIDDLE);
                                    setName(contactInfo.getDisplayName() + "(" + contactInfo.getMemberCount() + ")");
                                    mTitle.setTextColor(getContext().getResources().getColor(isMissedCall ? R.color.gray_6 : R.color.gray_7));
                                } else {
                                    mTitle.setEllipsize(TextUtils.TruncateAt.END);
                                    setName(contactInfo.getDisplayName());
                                }
                            } else {//会话列表
                                mTitle.setEllipsize(TextUtils.TruncateAt.END);
                                setName(contactInfo.getDisplayName());
                            }


                            setOAVerify(contactInfo.getOaIcon());

                            if (ContactUtil.isUser(contactInfo.getUid())) {
                                if ((contactInfo.getContactId() > 0 && !alwaysShowNickname) || TextUtils.isEmpty(contactInfo.getNickName())) {
                                    setFollowViewName(null);
                                } else {
                                    setFollowViewName((showSymbol ? "~" : "") + contactInfo.getNickName());
                                }
                            } else {
                                setFollowViewName(null);
                            }
                        }

                        if (contactInfo != null) {
                            setVip(contactInfo.isVip());
                            setBadgeWallet(contactInfo.isBadgeWallet());
                        }
                    }
                });
            }
        });
    }


    private void setOAVerify(String iconUrl) {
//        OAProfileUtil.setOAIcon(mFlag, iconUrl);
    }

    public void setVip(boolean isVip) {
        if (showVip) {
            if (isVip) {
                showVip();
            } else {
                hideVip();
            }
        } else {
            hideVip();
        }
    }

    public void showVip() {
        mVipBadge.setVisibility(View.VISIBLE);
    }

    public void hideVip() {
        mVipBadge.setVisibility(View.GONE);
    }

    private void setBadgeWallet(boolean isBadgeWallet) {
        if (showBadgeWallet) {
            if (isBadgeWallet) {
                showBadgeWallet();
            } else {
                hideBadgeWallet();
            }
        } else {
            hideBadgeWallet();
        }
    }

    public void showBadgeWallet() {
        mWalletBadge.setVisibility(View.VISIBLE);
    }

    public void hideBadgeWallet() {
        mWalletBadge.setVisibility(View.GONE);
    }

    private void setFollowViewName(@Nullable String name) {
        if (TextUtils.isEmpty(name)) {
            if (followView != null) {
                followView.setVisibility(GONE);
                followView.setText("");
                showFollowView = false;
            }
        } else {
            if (followView != null) {
                followView.setVisibility(VISIBLE);
                followView.setText(name);
                showFollowView = true;
            }
        }
    }

    private void setName(CharSequence nameOrigin) {
        this.nameNotProcessed = nameOrigin;
        if (textProcessor != null) {
            textProcessor.onSetText(mTitle, nameOrigin);
        } else {
            if (TextUtils.isEmpty(keywords)) {
                mTitle.setText(nameOrigin);
            } else {
                //关键字不为空时，设置高亮
                mTitle.setText(ColorStringUtils.setKeyWordHighlight(nameOrigin, keywords, highlightColor));
            }
        }
    }

    public void clear() {
        if (contactChangeListener != null) {
            UserSdkFactory.getSdk().unregisterContactListener(contactChangeListener);
        }
        contactChangeListener = null;
        textProcessor = null;
        mTitle.setText(null);
    }

    public void setTextProcessor(TextProcessor textProcessor) {
        this.textProcessor = textProcessor;
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
        if (followView != null) {
            followView.setVisibility(showFollowView ? visibility : GONE);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        if (contactChangeListener != null) {
            UserSdkFactory.getSdk().registerContactListener(contactChangeListener);
        }
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        if (contactChangeListener != null) {
            UserSdkFactory.getSdk().unregisterContactListener(contactChangeListener);
        }
        super.onDetachedFromWindow();
    }

    public void executeProcessor() {
        if (textProcessor != null) {
            textProcessor.onSetText(mTitle, nameNotProcessed);
        }
    }

    public String getTag2() {
        return tag2;
    }

    public void setTag2(String tag2) {
        this.tag2 = tag2;
    }

    public void setText(String nameCardNickName) {
        mTitle.setText(nameCardNickName);
    }

    public void setText(@StringRes int res) {
        mTitle.setText(res);
    }

    public void setTextSize(float textSizeSP) {
        mTitle.setTextSize(textSizeSP);
    }

    public void setTextSize(int unit, float textSize) {
        mTitle.setTextSize(unit, textSize);
    }

    public void setTextColor(@ColorInt int color) {
        mTitle.setTextColor(color);
    }

    public void setTextViewPaddingRelative(int start, int top, int end, int bottom) {
        mTitle.setPaddingRelative(start, top, end, bottom);
    }

    public interface TextProcessor {
        void onSetText(TextView view, CharSequence charSequence);
    }

    public String getTitleText() {
        if (mTitle == null) {
            return "";
        }
        return mTitle.getText().toString();
    }
}
